<template>
  <span>{{ tweeningValue }}</span>
</template>

<script>

  export default {
    name: "tween-number",

    props: {
      value: {
        required: true,
        default: 0
      },
      filter: {
        type: Function,
        default: _.currency,
      },
      isFilter: {
        type: Boolean,
        default: true
      }
    },
    data() {
      return {
        tweeningValue: 0
      }
    },
    watch: {
      value(newValue, oldValue) {
        this.tween(Number(oldValue), Number(newValue))
      }
    },
    mounted() {
      this.tween(0, Number(this.value))
    },
    methods: {
      tween(startValue, endValue) {
        const vm = this;
        let startDecimal = startValue.toString().split('.')[1];
        let endDecimal = endValue.toString().split('.')[1];
        startDecimal = startDecimal ? startDecimal.length : 0;
        endDecimal = endDecimal ? endDecimal.length : 0;
        const digits = startDecimal > endDecimal ? startDecimal : endDecimal;

        // function animate () {
        //   if (TWEEN.update()) {
        //     requestAnimationFrame(animate)
        //   }
        // }
        let current = {
          value: startValue,
        };

        TweenMax.to(current, .5, {
          value: endValue,
          roundProps: 'value',
          ease: Linear.easeNone,
          onUpdate: obj => {
            vm.tweeningValue = this.isFilter ? this.filter(current.value) : current.value;
          },
          onComplete: () => {
            vm.tweeningValue = this.isFilter ? this.filter(endValue) : endValue;
          }
        });
      }
    }
  }
</script>

<style scoped>

</style>
